import 'dart:convert';

import 'package:earclean/app/util/common_utils.dart';
import 'package:earclean/app/util/pay_utils.dart';
import 'package:get/get.dart';

import 'package:url_launcher/url_launcher.dart';
import 'package:webview_flutter/webview_flutter.dart';

class MessageController extends GetxController {
  // final title = ''.obs;
  final chat_url = ''.obs;

  final title = ''.obs;

  final progress = 0.0.obs;
  final canGoBack = false.obs;

  WebViewController? webViewController; // 添加一个controller

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    // loadData();
    // 我的订单
    // box.write("my_need_url", data['my_need_url'].toString());
    // // 我的钱包
    // box.write("my_account", data['my_account'].toString());
    // // 消息
    // box.write("chat_url", data['chat_url'].toString());
    //  chat_url.value = box.read('chat_url');
    super.onReady();
  }

  loadData() {
    chat_url.value = box.read('chat_url') ?? "";
    print(chat_url);
  }

  // loadData() {
  //   // 获取数据
  //   List chatdata = box.read('chatdata') ?? [];
  //   dataList.value = chatdata;
  //   dataList.refresh();
  // }

  // toChat(item) {
  //   Get.toNamed(Routes.CHAT, arguments: {
  //     "user_id": item['user_id'],
  //     "user_avatar": item['user_avatar'],
  //     "user_name": item['user_name'],
  //   })!
  //       .then((value) {
  //     loadData();
  //   });
  // }
  void messageHandle(JavascriptMessage message) {
    String jsmessage = message.message;

    print('=====jsmessage' + jsmessage);

    try {
      Map<String, dynamic> jsMap = json.decode(jsmessage);
      if (jsMap.isNotEmpty) {
        String type = jsMap["type"].toString();
        // 1、跳出APP外部在 safari 中打开，type=5,url=要打开的链接：
        // 2、内部H5跳转，type=15,url=要打开的链接
        // 3、重新获取消息未读数 type=999996：
        // 4、隐藏底部bar type=999997：
        // 5、显示底部bar type=999998：
        // 6、TD统计埋点 type=999999，两个参数：
        if (type == "999997") {
          canGoBack.value = true;
        } else if (type == "999998") {
          canGoBack.value = false;
        } else if (type == "pay") {
          PayUtils.wxpay(
              Map<String, dynamic>.from(jsMap["sign"]['data']['sign']));
        }
      }
    } catch (e) {
      print('prase error');
      print(e);
    }
  }

  void launchURL(Uri apkUrl) async {
    if (await canLaunchUrl(apkUrl)) {
      await launchUrl(
        apkUrl,
      );
    }
  }

  @override
  void onClose() {}
}
